import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter_ui/flavors/app_config.dart';

/// EHR WebView页面
///
/// 用于显示EHR系统的WebView页面
class EhrWebViewPage extends StatefulWidget {
  final String url;

  const EhrWebViewPage({super.key, required this.url});

  @override
  State<EhrWebViewPage> createState() => _EhrWebViewPageState();
}

class _EhrWebViewPageState extends State<EhrWebViewPage> {
  late final WebViewController _controller;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _initWebViewController();
  }

  void _initWebViewController() {
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageStarted: (String url) {
            setState(() {
              _isLoading = true;
            });
          },
          onPageFinished: (String url) {
            setState(() {
              _isLoading = false;
            });
          },
          onNavigationRequest: (NavigationRequest request) {
            // 可以在这里处理导航请求，例如拦截某些URL
            return NavigationDecision.navigate;
          },
        ),
      )
      ..loadRequest(Uri.parse(widget.url));
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        // 检查WebView是否可以返回上一页
        if (await _controller.canGoBack()) {
          await _controller.goBack();
          return false; // 阻止应用退出
        }
        return true; // 允许应用退出
      },
      child: Scaffold(
        appBar: AppBar(
          title: Text(AppConfig.instance.appName),
          leading: IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: () async {
              if (await _controller.canGoBack()) {
                await _controller.goBack();
              } else {
                if (context.mounted) {
                  Navigator.of(context).pop();
                }
              }
            },
          ),
          actions: [
            IconButton(
              icon: const Icon(Icons.refresh),
              onPressed: () {
                _controller.reload();
              },
            ),
          ],
        ),
        body: Stack(
          children: [
            WebViewWidget(controller: _controller),
            if (_isLoading)
              const Center(
                child: CircularProgressIndicator(),
              ),
          ],
        ),
      ),
    );
  }
}